<?php
defined('_JEXEC') or die('Restricted access');
require_once(JPATH_COMPONENT.DS.'data'.DS.'DAORoute.php');
require_once(JPATH_COMPONENT.DS.'dominio'.DS.'DTOFactory.php');

class JDAORoute implements DAORoute{
	
	public function __construct(){
		
	}
	
	private function multiObjectQuery($query){
		$db =& JFactory::getDBO();
		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		return $rows;
	}	
	
	private function singleObjectQuery($query){
		$db =& JFactory::getDBO();
		$db->setQuery( $query );
		$row = $db->loadObject();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		return $row;
	}
	
	public function getRoute($id){
		$row=$this->singleObjectQuery("SELECT * FROM #__sr_routes WHERE id=".$id);
		return DTOFactory::getInstance()->getDTORouteFromObject($row);
	}
	
	public function getRouteDesc($id){
		$row=$this->singleObjectQuery("SELECT id,userID,name,description,distance FROM #__sr_routes WHERE id=".$id);
		return DTOFactory::getInstance()->getDTORouteDescFromObject($row);
	}
	
	public function getUserCreatedRoutes($user){
		$rows=$this->multiObjectQuery("SELECT id,userID,name,description,distance FROM #__sr_routes WHERE userID=".$user);
		return DTOFactory::getInstance()->getDTORoutesDescFromObject($rows);
	}
	
	public function getUserRoutes($user){
		$rows=$this->multiObjectQuery("SELECT routes.id,routes.userID,name,description,distance FROM #__sr_routes AS routes 
									   INNER JOIN #__sr_userroutes AS userroutes ON routes.id=userroutes.routeID 
									   WHERE userroutes.userID=".$user);
		return DTOFactory::getInstance()->getDTORoutesDescFromObject($rows);
	}
	
	public function getNearestRoutes($location,$circleRadius,$maxDistance){
		
	}
	
	public function getNearestRoutesSimilar($location,$circleRadius,$maxDistance,$minDistance){
		
	}
	public function getRoutesDescByKeywords($keywords,$maxDistance){
		
	}
	
	public function getRoutesByDistance($maxDistance){
		
	}
	
	public function saveRoute($route){
		$row =& JTable::getInstance('routes', 'Table');
		$row->userID=$route->getUser()->get('id');
		$row->name=$route->getName();
		$row->description=$route->getDescription();
		$row->route=$route->getRawCoordinates();
		$row->distance=$route->getDistance();
		$row->elevation=$route->getElevation();
		if (!$row->store()){
			return false;
		}
		return $row->id;
	}
	
}

?>